package com.franklin.java.api.ui;

import com.franklin.java.api.ui.jpanel.AbstractComponent;
import com.franklin.java.utils.SwingUtils;
import com.franklin.plugins.common.collection.PrettyArrayList;
import com.intellij.icons.AllIcons;
import com.intellij.ui.components.JBLabel;
import org.apache.commons.lang3.ArrayUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.List;

/**
 * 对ActionListener进行包装，添加提示功能
 * @author Franklin
 * @since 2021/9/26 11:23
 */
public abstract class MessageActionListener<T> extends AbstractComponent implements ActionListener {

    protected final String successMessage;
    protected final boolean showResult;
    protected final List<JPanel> showMessagePanels;

    protected MessageActionListener(String successMessage, boolean showResult, JPanel ... showMessagePanels) {
        if (ArrayUtils.isEmpty(showMessagePanels)){
            throw new IllegalArgumentException();
        }
        this.successMessage = successMessage;
        this.showResult = showResult;
        this.showMessagePanels = new PrettyArrayList<>();
        Collections.addAll(this.showMessagePanels,showMessagePanels);
    }

    @Override
    public final void actionPerformed(ActionEvent e) {
        try {
            T result = handleActionEvent(e);
            if (!showResult){
                showMessage(true,successMessage);
            }else {
                showMessage(true,result.toString());
            }
        } catch (Exception exception) {
            //连接失败
            showMessage(false,exception.getMessage());
        }
        lastOperation();
    }

    /**
     * 真正处理Event的方法<br>
     * @author Franklin
     * @since 2021/9/25 14:53
     * @param e:
     * @return void
     */
    protected abstract T handleActionEvent(ActionEvent e) throws Exception;

    private void showMessage(boolean success, String message){
        this.showMessagePanels.forEach(showMessagePanel -> SwingUtils.showTestMessage(showMessagePanel,success,message));
    }

    @Override
    public JComponent getMainPanel() {
        throw new UnsupportedOperationException();
    }

    public void addShowMessagePanel(JPanel showMessagePanel){
        this.showMessagePanels.add(showMessagePanel);
    }

    protected void lastOperation(){

    }
}
